package com.yxx.data.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yxx.data.common.ConstastMapWord2Int;
import com.yxx.data.common.DataConstast;
import com.yxx.data.domain.Wound;
import com.yxx.data.service.WoundService;
import com.yxx.data.vo.WoundVo;
import com.yxx.sys.common.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yxx
 * @since 2022-05-16
 */
@RestController
@RequestMapping("/wound")
@Api("创面信息控制器")
public class WoundController {

  @Autowired
  WoundService woundService;


  @GetMapping("/loadAllWound")
  @ApiOperation("查询创面信息")
  public DataGridView loadAllWound(WoundVo woundVo) {
    IPage<Wound> page = new Page<Wound>(woundVo.getPage(), woundVo.getLimit());
    QueryWrapper<Wound> queryWrapper = new QueryWrapper<Wound>();

    queryWrapper.eq(StrUtil.isNotBlank(woundVo.getPatientId()), "patient_id", woundVo.getPatientId());
    queryWrapper.like(StrUtil.isNotBlank(woundVo.getReason()), "reason", woundVo.getReason());
    queryWrapper.eq(woundVo.getArea() != null, "area", woundVo.getArea());
    queryWrapper.like(StrUtil.isNotBlank(woundVo.getPosition()), "position", woundVo.getPosition());
//    queryWrapper.eq(woundVo.getDepth() != null && woundVo.getDepth() != -1, "depth", woundVo.getDepth());
    queryWrapper.orderByDesc("id");
    woundService.page(page, queryWrapper);
    return new DataGridView(page.getTotal(), page.getRecords());
  }


  @PostMapping("/addWound")
  @ApiOperation("添加创面信息")
  public Result addWound(WoundVo woundVo) {
    //修改图片名 包括上传了的图片的和vo中的，转换为：张三D12
    String img_name = woundVo.getPatientId().toString() +"D" +woundVo.getAfterHurtDay();
    woundVo.setPictureId(img_name);
    woundVo.setName(AppSecureUtils.getEncryptData(woundVo.getName()));
    String imgPath = AppFileUtils.renameFile(woundVo.getPicturePath(), img_name,AppFileUtils.UPLOAD_CM_PATH);
    woundVo.setPicturePath(imgPath);

    woundVo.setCreatedTime(LocalDateTime.now());
    woundVo.setChangeTime(LocalDateTime.now());
    try {
      woundService.save(woundVo);
      return Result.ADD_SUCCESS;
    } catch (Exception e) {
      e.printStackTrace();
      return Result.ADD_REEOR;
    }
  }

  @PostMapping("/addWoundZip")
  @ApiOperation("用zip的形式添加创面信息")
  public DataGridView addWoundZip(MultipartFile mf) {
    String zipFile = AppFileUtils.UPLOAD_CM_PATH + AppFileUtils.uploadFile(mf,AppFileUtils.UPLOAD_CM_PATH);
    String zipFileDest = zipFile.replaceAll(".zip", "");
    AppFileUtils.unZip(zipFile, zipFileDest);
    String sourImgDir = zipFileDest + "/img";
    String[] zipFileDestSplit = zipFileDest.split("/");
    String destImgDir = zipFileDest.replaceAll(zipFileDestSplit[zipFileDestSplit.length - 1], "");


    String excelFilePath = zipFileDest + "/img.xlsx";
    String dst_excelFilePath = zipFileDest + "/dst_img.xlsx";
    //读入数据 修改数据
    ExcelReader reader = ExcelUtil.getReader(FileUtil.file(excelFilePath));
    List<List<Object>> excelContent = reader.read();
    //将中文替换为字段名 然后写回
    excelContent.set(0, DataConstast.excel_title_en_woundList);


    ExcelWriter writer = ExcelUtil.getWriter(dst_excelFilePath);
    List<List<Object>> dstExcelContent=new ArrayList<>();
    dstExcelContent.add(excelContent.get(0));

    for (int i = 1; i < excelContent.size(); i++) {
      List<Object> objects = excelContent.get(i);
      //姓名转换
      objects.set(1, AppSecureUtils.getEncryptData(Convert.toStr(objects.get(3))));
      //性别转换
      objects.set(3, ConstastMapWord2Int.sexMap.get(objects.get(3)));
      //烧伤深度转化
      objects.set(9, ConstastMapWord2Int.depthMap.get(objects.get(9)));
      //创面感染
      objects.set(11, ConstastMapWord2Int.trueFalseMap.get(objects.get(11)));
      //冷疗
      objects.set(14, ConstastMapWord2Int.trueFalseMap.get(objects.get(14)));
      //胶原酶使用
      objects.set(15, ConstastMapWord2Int.trueFalseMap.get(objects.get(15)));
      //敷料类型
      objects.set(16, ConstastMapWord2Int.fuLiaoTypeMap.get(objects.get(16)));
      //清创
      objects.set(18, ConstastMapWord2Int.trueFalseMap.get(objects.get(18)));
      //清创时间
      Date qingChuangTime = DateUtil.parse(objects.get(19).toString());
      String qingChuangTimeStr = DateUtil.formatDate(qingChuangTime);
      objects.set(19, qingChuangTimeStr);
      //植皮
      objects.set(20, ConstastMapWord2Int.trueFalseMap.get(objects.get(20)));
      //植皮时间
      Date zhiPiTime = DateUtil.parse(objects.get(21).toString());
      String zhiPiTimeStr = DateUtil.formatDate(zhiPiTime);
      objects.set(21, zhiPiTimeStr);
      //植皮厚度
      objects.set(22, ConstastMapWord2Int.zhiPiDepthMap.get(objects.get(22)));

      //根据患者编号查找图片文件夹 遍历内部图片 并创建n条excel行
      File[] patientImgs = FileUtil.ls(sourImgDir+"/"+objects.get(0));
      for (File patientImg : patientImgs) {
        // 1524M3.jpg 1524D7.jpg
        String patientImgName = patientImg.getName();
        String patientImgRelativePath =AppFileUtils.getRelativePath(patientImg.getAbsolutePath());

        Integer afterHurtDay;
        if(patientImgName.contains("D")){
          afterHurtDay = Integer.parseInt(patientImgName.split("\\.")[0].split("D")[1]);

        }else if(patientImgName.contains("M")){
          afterHurtDay = Integer.parseInt(patientImgName.split("\\.")[0].split("M")[1])*30+1;
        }else {
          afterHurtDay = Integer.parseInt(patientImgName.split("\\.")[0].split("Y")[1])*365;
        }
        //两类重命名 一类是YMD 全部转换为D，如将1524M3.jpg改成1524D90.jpg；另一类是将原来错误的名字改对
        patientImgRelativePath=AppFileUtils.renameFile(patientImgRelativePath, objects.get(0) + "D" + afterHurtDay,AppFileUtils.UPLOAD_CM_PATH);
        ArrayList<Object> excelRow = CollUtil.newArrayList(objects);
        excelRow.add(afterHurtDay);
        dstExcelContent.add(excelRow);
        File patientImgNew = FileUtil.file(AppFileUtils.UPLOAD_CM_PATH + patientImgRelativePath);
        FileUtil.move(patientImgNew,FileUtil.file(destImgDir + "/" + patientImgNew.getName()), true);
      }
    }
    reader.close();
    writer.write(dstExcelContent,true);
    writer.close();
    //使用bean的形式读入数据
    reader = ExcelUtil.getReader(FileUtil.file(dst_excelFilePath));
    List<Wound> wounds = reader.readAll(Wound.class);
    //问题记录
    List<String> failList = new ArrayList();
    for (Wound wound : wounds) {
      wound.setPictureId(wound.getPatientId().toString()+"D"+wound.getAfterHurtDay());
      String picturePath = AppFileUtils.existTodayFile(wound.getPictureId());
      if (StrUtil.isBlank(picturePath)) {
        failList.add(wound.getPictureId());
        continue;
      }
      wound.setPicturePath(picturePath);
      wound.setChangeTime(LocalDateTime.now());
      wound.setCreatedTime(LocalDateTime.now());
      woundService.save(wound);
    }
    reader.close();
    //删除压缩包和压缩文件夹
    AppFileUtils.removeFile(new File(zipFile));
    AppFileUtils.removeDirectory(new File(zipFileDest));
    if (failList.size() > 0) {
      return new DataGridView(SysConstast.ERROR, failList);
    }
    return new DataGridView(SysConstast.OK, failList);
  }

  @PostMapping("/loadWoundZip")
  @ApiOperation("用zip的形式下载创面信息")
  public DataGridView loadWoundZip(Wound wound) {
    QueryWrapper<Wound> queryWrapper = new QueryWrapper<Wound>();

    queryWrapper.like(StrUtil.isNotBlank(wound.getName()), "name", wound.getName());
    queryWrapper.like(StrUtil.isNotBlank(wound.getReason()), "reason", wound.getReason());
    queryWrapper.eq(wound.getArea() != null, "area", wound.getArea());
    queryWrapper.like(StrUtil.isNotBlank(wound.getPosition()), "position", wound.getPosition());
//    queryWrapper.eq(wound.getDepth() != null && wound.getDepth() != -1, "depth", wound.getDepth());
    queryWrapper.orderByDesc("id");
    List<Wound> list = woundService.list(queryWrapper);
    for (Wound tmp_wound : list) {
      tmp_wound.setName(AppSecureUtils.getDecryptData(tmp_wound.getName()));
    }
    String woundZipPath = AppFileUtils.createWoundZip(list);
    Map map = new HashMap();
    map.put("path", woundZipPath);
    return new DataGridView(SysConstast.OK, map);
  }

  @PostMapping("/deleteWoundZip")
  @ApiOperation("用zip的形式下载创面信息之后 把zip包删除掉")
  public Result deleteWoundZip(String path) {
    boolean b = AppFileUtils.removeFile(FileUtil.file(AppFileUtils.DOWNLOAD_PATH + path));
    if(!b) return Result.DELETE_REEOR;
    return Result.DELETE_SUCCESS;
  }


  @PostMapping("/updateWound")
  @ApiOperation("更新创面信息")
  public Result updateWound(WoundVo woundVo) {
    try {
      woundVo.setPictureId(woundVo.getPatientId().toString()+"D"+woundVo.getAfterHurtDay());
      String picturePath = AppFileUtils.renameFile(woundVo.getPicturePath(), woundVo.getPictureId(),AppFileUtils.UPLOAD_CM_PATH);
      woundVo.setPicturePath(picturePath);


      boolean c =
      woundService.lambdaUpdate()
              .set(Wound::getPicturePath, woundVo.getPicturePath())
              .set(Wound::getPatientId, woundVo.getPatientId())
              .set(Wound::getName, woundVo.getName())
              .set(Wound::getAge, woundVo.getAge())
              .set(Wound::getSex, woundVo.getSex())
              .set(Wound::getHeight, woundVo.getHeight())
              .set(Wound::getWeight, woundVo.getWeight())
              .set(Wound::getAfterHurtDay, woundVo.getAfterHurtDay())
              .set(Wound::getCureDay, woundVo.getCureDay())
              .set(Wound::getReason, woundVo.getReason())
              .set(Wound::getArea, woundVo.getArea())
              .set(Wound::getPosition, woundVo.getPosition())
              .set(Wound::getHasInfected, woundVo.getHasInfected())
              .eq(Wound::getPictureId, woundVo.getPictureId())
              .update();

//      boolean b = woundService.updateById(woundVo);


      if(!c) return Result.UPDATE_REEOR;
      return Result.UPDATE_SUCCESS;
    } catch (Exception e) {
      e.printStackTrace();
      return Result.UPDATE_REEOR;
    }
  }

  @PostMapping("/deleteWound")
  @ApiOperation("删除创面信息")
  public Result deleteWound(Integer id, String picturePath) {
    try {
      boolean b = AppFileUtils.removeFile(new File(AppFileUtils.UPLOAD_CM_PATH + picturePath));
      if(!b) return Result.DELETE_REEOR;
      woundService.removeById(id);
      return Result.DELETE_SUCCESS;
    } catch (Exception e) {
      e.printStackTrace();
      return Result.DELETE_REEOR;
    }
  }


}
